package com.jsb.laundry.common.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostUtil {

    /**
     * 发送HTTP POST请求
     * @param url 请求URL
     * @param contentType 请求正文类型，如application/json、application/x-www-form-urlencoded等
     * @param requestData 请求正文数据
     * @return 响应内容字符串
     * @throws Exception
     */
    public static String doPost(String url, String contentType, String requestData) {
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(6000);
            connection.setReadTimeout(6000);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", contentType);
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            writer.write(requestData);
            writer.flush();
            writer.close();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder responseBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    responseBuilder.append(line);
                }
                reader.close();
                return responseBuilder.toString();
            } else {
                return "HTTP POST request failed with response code: " + connection.getResponseCode();
            }
        } catch (Exception e) {
            return "HTTP POST request failed: " + e.getMessage();
        }
    }


}
